namespace DaemonAPI.AppStart
{
    using Daemon.Common.Auth;
    using Daemon.Data.Infrastructure.Configuration;
    using Daemon.Data.Infrastructure.Auth;
    using Daemon.Middleware;
    using IdentityModel;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    public class ContextInfoProvider : IContextInfoProvider
    {
        private const string SELECT = "@fields";
        private const string DISTINCT = "Distinct";

        private IAuthInfo _authInfo;

        public ContextInfoProvider()
        {
            var request = HttpContextHelper.Current.Request;
            var userName = request.HttpContext.User.Claims?.FirstOrDefault(r => r.Type.ToLower() == JwtClaimTypes.Name.ToLower());
            if (!string.IsNullOrEmpty(userName?.Value))
            {
                this._authInfo = ServiceLocator.Resolve<ClientAuthCache>().GetAuthInfoByClientUser(userName.Value);
            }
        }

        public string RequestOrigin { get; }

        public string Version { get; }

        public string SessionItemId { get; }

        public DateTime? ClientDateTime { get; }

        public IAuthInfo AuthInfo
        {
            get
            {
                if (_authInfo == null)
                {
                    var request = HttpContextHelper.Current.Request;
                    var userName = request.HttpContext.User.Claims?.FirstOrDefault(r => r.Type.ToLower() == JwtClaimTypes.Name.ToLower());
                    if (!string.IsNullOrEmpty(userName?.Value))
                    {
                        this._authInfo = ServiceLocator.Resolve<ClientAuthCache>().GetAuthInfoByClientUser(userName.Value);
                    }
                }
                return _authInfo;
            }
        }

        public string IPAddress { get; }

        public string Host { get; }

        public string UserAgent { get; }

        public IEnumerable<string> SelectFields { get; }

        public string CurrentVersion { get; }

        public string Prefix { get; }
    }
}